package com.go.where.manager.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.go.where.manager.dao.BannerDao;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.BannerInfo;
import com.go.where.manager.pojo.user.UserInfoVO;
import com.go.where.manager.service.BannerService;

@Service("bannerService")
public class BannerServiceImpl implements BannerService {

	@Resource(name = "bannerDao")
	private BannerDao bannerDao;

	@Override
	public BannerInfo queryByPrimartKey(String cid) {
		return bannerDao.getByKey(cid);
	}

	@Override
	public Pagination<BannerInfo> queryPage(BannerInfo bannerInfo) {
		Integer count = bannerDao.totalCount(bannerInfo);
		bannerInfo.calculate();
		List<BannerInfo> list = bannerDao.queryList(bannerInfo);
		Pagination<BannerInfo> page = bannerDao.queryPagination(count, list,
				bannerInfo);
		return page;
	}

	@Override
	public int save(BannerInfo bannerInfo, UserInfoVO currentUser) {
		BannerInfo ba = bannerDao.queryByOrderAndBelong(bannerInfo);
		if (ba != null) {
			bannerDao.deleteByKey(ba.getId());
		}
		bannerInfo.setId(UUID.randomUUID().toString());
		bannerInfo.setPublishTime(new Date());
		bannerInfo.setUserId(currentUser.getUserId());
		return bannerDao.insert(bannerInfo);
	}

	@Override
	public int update(BannerInfo bannerInfo, UserInfoVO currentUser) {
		BannerInfo bi = new BannerInfo();
		bi.setBannerBelong(bannerInfo.getBannerBelong());
		bi.setBannerOrder(bannerInfo.getOldBannerOrder());
		if (!bannerInfo.getBannerOrder()
				.equals(bannerInfo.getOldBannerOrder())) {
			List<BannerInfo> list = bannerDao.queryByBelong(bannerInfo);
			BannerInfo ba = bannerDao.queryByOrderAndBelong(bi);
			if (ba != null && list.size() > 1) {
				bannerDao.deleteByKey(ba.getId());
			}
		}
		bannerInfo.setUpdateTime(new Date());
		bannerInfo.setUserId(currentUser.getUserId());
		return bannerDao.update(bannerInfo);
	}

}
